//
//  ReadMeViewController.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 16/3/10.
//  Copyright © 2016年 李萍. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class ReadMeViewController: UIViewController, UIWebViewDelegate {
    var webView: UIWebView!
    var html: String = ""
    var nameSpace: String = ""
    var isFinishedLoad: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.title = "ReadMe"
        self.view.backgroundColor = UIColor.whiteColor()
        
        self.initSubView()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    //初始化webView
    func initSubView() {
        webView = UIWebView()
//        webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
        webView.delegate = self
        webView.scrollView.bounces = false
        webView.opaque = false
        webView.backgroundColor = UIColor.clearColor()
        webView.scalesPageToFit = false
        webView.hidden = true
        
        self.view.addSubview(webView)
        
        webView.translatesAutoresizingMaskIntoConstraints = false
        
        self.view .addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[webView]|",
            options: NSLayoutFormatOptions(),
            metrics: nil,
            views: ["webView":webView]))
        
        self.view .addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|",
            options: NSLayoutFormatOptions(),
            metrics: nil,
            views: ["webView":webView]))
        
        self.fetchProjectReadME()
    }
    
    //获取数据
    func fetchProjectReadME() {
        let userinfos = UserInfos()
        let private_token = userinfos.getprivateToken()
        let strUrl = "https://git.oschina.net/api/v3/projects/\(nameSpace)/readme?private_token=\(private_token)"
        
        Alamofire.Manager.sharedInstance.request(Method.GET, strUrl).responseJSON { response in
            if let results = response.result.value {
                let json = JSON(results)
                self.html = json["content"].stringValue
                
                self.webView.loadHTMLString(self.html, baseURL: nil)
                print(self.html)
            } else {
                self.isFinishedLoad = true
                self.webView.loadHTMLString("该项目暂无Readme文件", baseURL: nil)
            }
        }
    }
    
    //
    func webViewDidFinishLoad(webView: UIWebView) {
        if isFinishedLoad {
            webView.hidden = false
            webView.scalesPageToFit = true
            return
        }
        
        let bodyWidth = webView.stringByEvaluatingJavaScriptFromString("document.body.scrollWidth ")
        let widthBody = Int(bodyWidth!)
        let adjustedHTML = self.htmlAdjustWithPageWidth(CGFloat(widthBody!), html: self.html, webView: webView)
        
        webView.loadHTMLString(adjustedHTML, baseURL: nil)
        isFinishedLoad = true
    }
    
    func htmlAdjustWithPageWidth(pageWidth: CGFloat, html: String, webView: UIWebView) -> String {
        let initialScale = webView.frame.size.width/pageWidth
        
        let header = "<meta name=\"viewport\" content=\" initial-scale=\(initialScale), minimum-scale=0.1, maximum-scale=2.0, user-scalable=yes\">"
        let newHTML = "<html><head>\(header)</head><body>\(html)</body></html>"
        
        return newHTML
    }
}
